package com.cungmua.app.task;

import android.util.Log;

import com.cungmua.app.handler.BaseAuthenticatedRequestHandler;
import com.cungmua.app.model.request.AuthenticatedRequest;
import com.cungmua.app.model.request.LoginRequest;
import com.cungmua.app.model.response.CungMuaResponse;
import com.cungmua.app.model.response.LoginResponse;
import com.cungmua.app.net.CungMuaAPI;

/**
 * Created by kelvin.nguyen on 6/16/14.
 */
public abstract class AuthenticatedTask<Params extends AuthenticatedRequest, Progress, Result extends CungMuaResponse>
        extends BaseRequestTask<Params, Progress, Result> {

    @Override
    protected Result doInBackground(Params... params) {
        Result result =  super.doInBackground(params);

        if (result == null)
            return result;

        Log.d("Test Token==================", result.getMessage());

        if (result.getCode() == 1002) {
            try {

                LoginRequest lastLoginRequest = getHandler().getLastLoginRequest();

                LoginResponse response = CungMuaAPI.getService().login(lastLoginRequest.toFieldMap());
                lastLoginRequest.setAuthToken(response.getData().getToken());

                getHandler().setLastLoginRequest(lastLoginRequest);

                if (response.getCode() == 0) {
                    String newToken = response.getData().getToken();
                    params[0].setToken(newToken);
                    getHandler().setCurrentUser(response.getData());

                    result = super.doInBackground(params);
                } else {
                    getHandler().reLoginFailed(response.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();

                getHandler().reLoginFailed("");
            }
        }

        return result;
    }

    @Override
    protected abstract BaseAuthenticatedRequestHandler getHandler();
}
